package com.centaline.androidsalesblog.activities;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.adapter.CityListAdapter;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.model.databaseobject.CityDo;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.trello.rxlifecycle.ActivityEvent;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;

import ca.barrenechea.widget.recyclerview.decoration.StickyHeaderDecoration;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 城市列表
 */
public class CityListActivity extends BaseActivity {

    private RecyclerView recyclerView;

    private CityListAdapter cityListAdapter;
    private ArrayList<CityDo> cityDoArrayList = new ArrayList<>();//真实城市列表
    private ArrayList<CityDo> cityDoList = new ArrayList<>();//显示的城市列表
    private CityDo cityDo = new CityDo();//定位使用
    private CityDo preCityDo;//上次选择城市

    private LocationClient locationClient;
    private boolean forceSelect;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_city_list;
    }

    @Override
    protected void findViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    }

    @Override
    protected void initViews() {
        forceSelect = getIntent().getBooleanExtra(ExtraConstant.ForceSelectCity, false);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.title_city_list);
            if (!forceSelect)
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        cityListAdapter = new CityListAdapter(this, cityDoList, forceSelect);
        cityListAdapter.setRecyclerViewItemOnClickListener(new RecyclerViewItemOnClickListener<CityDo>() {
            @Override
            public void onItemOnClick(CityDo cityDo, int tag) {
                if (tag == 0) {
                    switch (cityListAdapter.getLocationStatus()) {
                        case 1://定位成功
                            if (TextUtils.isEmpty(cityDo.getCode())) {
                                snack(getString(R.string.snack_city_unable));
                            } else {
                                if (!AppConstant.CityCode.equals(cityDo.getCode())) {
                                    Intent intent = new Intent();
                                    intent.putExtra(ExtraConstant.CityDo, cityDo);
                                    AppConstant.setNearbyEnable(CityListActivity.this,
                                            cityDo.getCode().equalsIgnoreCase(cityDoList.get(0).getCode()));
                                    if (preCityDo != null) {
                                        intent.putExtra(ExtraConstant.PreCityDo, preCityDo);
                                    }
                                    setResult(RESULT_OK, intent);
                                }
                                finish();
                            }
                            break;
                        case 2://定位失败
                            cityDo.setCityName("定位中...");
                            cityListAdapter.setLocationStatus(0);
                            startLocation();
                            break;
                        default:
                            break;
                    }
                } else {
                    if (!AppConstant.CityCode.equals(cityDo.getCode())) {
                        Intent intent = new Intent();
                        intent.putExtra(ExtraConstant.CityDo, cityDo);
                        AppConstant.setNearbyEnable(CityListActivity.this,
                                cityDo.getCode().equalsIgnoreCase(cityDoList.get(0).getCode()));
                        if (preCityDo != null) {
                            intent.putExtra(ExtraConstant.PreCityDo, preCityDo);
                        }
                        setResult(RESULT_OK, intent);
                    }
                    finish();
                }
            }
        });
        recyclerView.setAdapter(cityListAdapter);
        recyclerView.addItemDecoration(new StickyHeaderDecoration(cityListAdapter));
        locationClient = MyLocation.getLocationClient();
        cityDo.setCityName("定位中...");
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        cancelLoadingDialog();
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                final String cityName = bdLocation.getCity();
                                if (!TextUtils.isEmpty(cityName)) {
                                    cityDo.setCityName(cityName);
                                    cityDoList.remove(0);
                                    for (CityDo cityDo : cityDoArrayList) {
                                        if (cityName.contains(cityDo.getCityName()) ||
                                                cityDo.getCityName().contains(cityName)) {
                                            cityDoList.add(0, cityDo);
                                            cityListAdapter.setLocationStatus(1);
                                            break;
                                        }
                                    }
                                    if (cityDoArrayList.size() == cityDoList.size()) {
                                        cityDoList.add(cityDo);
                                    }
                                }
                                break;
                            default:
                                cityDo.setCityName(getString(R.string.city_location_error));
                                cityDoList.remove(0);
                                cityDoList.add(0, cityDo);
                                cityListAdapter.setLocationStatus(2);
                                snack("定位失败");
                                break;
                        }
                    }
                });

        request();
    }

    private void request() {
        showLoadingDialog();
        RxRequest.cityList(CityListActivity.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<CityDo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Subscriber<ArrayList<CityDo>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        netWorkUnable();
                    }

                    @Override
                    public void onNext(ArrayList<CityDo> cityDos) {
                        updateCityList(cityDos);
                        cityDoList.clear();
                        cityDoList.add(cityDo);
                        cityDoList.addAll(cityDos);
                        cityListAdapter.notifyDataSetChanged();
                        startLocation();
                    }
                });
    }

    /**
     * 更新本地数据
     */
    private void updateCityList(final ArrayList<CityDo> cityDos) {
        cityDoArrayList.clear();
        cityDoArrayList.addAll(cityDos);
        if (!TextUtils.isEmpty(AppConstant.CityCode)) {
            for (CityDo cityDo : cityDos) {
                if (AppConstant.CityCode.equals(cityDo.getCode()))
                    preCityDo = cityDo;
            }
        }
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                DataSupport.deleteAll(CityDo.class);
                DataSupport.saveAll(cityDos);
            }
        }).compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                    }
                });
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        locationClient.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (forceSelect && keyCode == KeyEvent.KEYCODE_BACK) {
            snack(getString(R.string.snack_force_select_city));
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
